package com.bw.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.bw.AssetInfo;
import com.bw.Dict;
import com.bw.mapper.AssetMapper;
import com.bw.service.AssetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AssetServiceImpl implements AssetService {

    @Autowired
    AssetMapper assetMapper;


    @Transactional
    //  转账
    @Override
    public AssetInfo add(AssetInfo assetInfo) {
        //非空校验，“*”非空字段
//        if (assetInfo.getTypeId() == null){
//            throw new RuntimeException("资产类别不为空");
//        }
        // 断言 （用在单元测试里）  断定这个参数不是null， 如果是null就报错
        Assert.notNull(assetInfo.getTypeId(),"资产类别不为空");
        Assert.notNull(assetInfo.getSourceId(),"资产来源不为空");
        //   校验字符串用  notBlank
        Assert.notBlank(assetInfo.getName(),"资产名称不为空");
        Assert.notNull(assetInfo.getPrice(),"价格不为空");
        Assert.notBlank(assetInfo.getCreateTime(),"日期不为空");

        //资产编号唯一性校验
        AssetInfo assetInfoDB =  assetMapper.selectByNum(assetInfo.getNum());

        if (assetInfoDB != null){
            throw new RuntimeException("资产编号不能重复");
        }

        //购入价格校验，必须为数值类型
        String price = assetInfo.getPrice();
        boolean number = NumberUtil.isNumber(price);
        if (!number){
            throw new RuntimeException("价格必须为数值类型");
        }
        //控制打印方法参数
        System.out.println("方法的入参是 " + JSON.toJSONString(assetInfo));

        assetMapper.add(assetInfo);

        System.out.println("添加成功。数据库的主键id是" + assetInfo.getId());

        return assetInfo;
    }

    @Override
    public AssetInfo selectByNum(String num) {
        // 查询 页面要显示的数据
        AssetInfo assetInfoDB =  assetMapper.selectByNum(num);

        List<Dict> typeList  = assetMapper.selectType();
        assetInfoDB.setTypeList(typeList);
        List<Dict> sourceList  = assetMapper.selectSource();
        assetInfoDB.setSourceList(sourceList);
        return assetInfoDB;
    }
}
